import Axios from 'axios'
import { isJSON } from './utils'

class AJAX {
  constructor(opt){
    this.url = typeof opt.url === 'string' ? opt.url : null
    this.method = (opt.type).toLowerCase() || 'get'
    this.data = opt.data || {}
    this.headers = isJSON(opt.headers) && opt.headers || {}
    this.timeout = opt.timeout || 2000
    this.withCredentials = opt.withCredentials || false
    this.auth = isJSON(opt.auth) && opt.auth || {}
    this.responseType = opt.responseType || 'json'
    this.onUploadProgress = typeof opt.onUploadProgress === 'function' ? opt.onUploadProgress : null
    this.onDownloadProgress = typeof opt.onDownloadProgress === 'function' ? opt.onDownloadProgress :
    this.source = opt.source || null
    null

    return this.init()
  }

  init() {
    this.dataType = this.createDataType()
    this.ajax = this.createAxios
    return this.ajax()
  }

  createDataType() {
    const type = this.method
    if(type === 'get')
      return 'params'
    else return 'data'
  }

  createAxios() {
    const opt = this.initAxios()
    return Axios(opt)
  }

  initAxios() {
    const url = this.url
    const method = this.method
    const headers = this.headers
    const timeout = this.timeout
    const withCredentials = this.withCredentials
    const auth = this.auth
    const responseType = this.responseType
    const onUploadProgress = this.onUploadProgress
    const onDownloadProgress = this.onDownloadProgress
    const cancelToken = this.source && this.source.token

    let opt = {
      url,
      method,
      headers,
      timeout,
      withCredentials,
      auth,
      responseType,
      onUploadProgress,
      onDownloadProgress,
      cancelToken
    }
    if(cancelToken)
      opt.cancelToken = cancelToken

    opt[this.dataType] = this.data

    return opt

  }
}

const ajax = (opt) => {
  return new AJAX(opt)
}

const Source = function() {
  const CancelToken = Axios.CancelToken
  const source = CancelToken.source()
  source.abort = source.cancel
  return source
}

export { Source }

export default ajax
